package pe.gob.foncodes.ssa.web.listener;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cuando se destruya la sesion, MySessionListener tendra que hacer
 * un logout. Ademas, a la primera solicitud del usuario, este filter
 * se encendera y redireccionara al usuario a la pagina inicial (o a una
 * pagina de "Sesion Expirada") si la sesion no es valida
 */
public class SessionTimeoutFilter implements Filter {

    private String timeoutPage = "index.jsp";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request,
            ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            // is session expire control required for this request?

            if (isSessionControlRequiredForThisResource(httpServletRequest)) {

                // is session invalid?

                if (isSessionInvalid(httpServletRequest)) {

                    String timeoutUrl = httpServletRequest.getContextPath()
                            + "/" + getTimeoutPage();
                    System.out.println("Session is invalid! redirecting to timeoutpage : " + timeoutUrl);
                    httpServletResponse.sendRedirect(timeoutUrl);
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * No se deberia  revisar la sesion de algunas paginas
     * Por ejemplo: para la pagina de login o la pagina de
     * Sesion expirada.
     */
    private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {
        String requestPath = httpServletRequest.getRequestURI();
        boolean controlRequired = !StringUtils.contains(requestPath, getTimeoutPage());
        return controlRequired;
    }

    private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
        boolean sessionInValid =
                (httpServletRequest.getRequestedSessionId() != null) && !httpServletRequest.isRequestedSessionIdValid();

        return sessionInValid;
    }

    @Override
    public void destroy() {
    }

    public String getTimeoutPage() {
        return timeoutPage;
    }

    public void setTimeoutPage(String timeoutPage) {
        this.timeoutPage = timeoutPage;
    }
}
